package com.zd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zd.config.PageResult;
import com.zd.config.Result;
import com.zd.entity.Admin;
import com.zd.mapper.AdminMapper;
import com.zd.service.IAdminService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zd.utils.JwtTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author TSP
 * @since 2021-08-22
 */
@Service
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements IAdminService {

    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private PasswordEncoder passwordEncoder;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private AdminMapper adminMapper;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    /**
     * 管理员登录返回token
     *
     * @param username
     * @param password
     * @param request
     * @return
     */
    @Override
    public Result login(String username, String password, HttpServletRequest request) {
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);
        if (userDetails == null || passwordEncoder.matches(password, userDetails.getPassword())) {
            return Result.error("用户名、密码或者身份不正确!");
        }
        if (!userDetails.isEnabled()) {
            return Result.error("账号被禁用，请联系管理员!");
        }
        //设置用户对象至SpringSecurity全局上下文，方便其他地方使用
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(userDetails,
                null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        //生成token
        String token = jwtTokenUtil.generatorToken(userDetails);
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("tokenHead", tokenHead);
        tokenMap.put("token", token);
        return Result.success("登录成功", tokenMap);
    }


    /**
     * 根据用户名获取用户
     *
     * @param username
     * @return
     */
    @Override
    public Admin getAdminByUserName(String username) {
        //还需要做程序健壮性代码补充
        return adminMapper.selectOne(new QueryWrapper<Admin>().eq("userName", username).eq("enabled", true));
    }

    /**
     * 获取admin的分页数据，基于MyBatisPlus
     *
     * @param currentPage
     * @param size
     * @return
     */
    @Override
    public PageResult getAllAdminByPage(Integer currentPage, Integer size) {
        //开启分页
        Page<Admin> page = new Page<>(currentPage, size);
        //获取分页数据
        IPage<Admin> iPage = adminMapper.getAllAdminByPage(page);
        //生成分页查询结果
        return new PageResult(iPage.getTotal(), iPage.getRecords());
    }
}
